package com.huanxing.cloud.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.web.client.RestTemplate;

/**
 * 资源服务器配置
 *
 * @author lijx
 * @version 1.0
 * @date 2022/5/3 14:07
 */
@Slf4j
public class HxResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
    @Autowired
    protected RemoteTokenServices remoteTokenServices;
    @Autowired
    private PermitAllUrlProperties permitAllUrlProperties;
    @Autowired
    private HxAuthenticationEntryPointImpl hxAuthenticationEntryPoint;
    @Autowired
    private HxAccessDeniedHandler hxAccessDeniedHandler;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @description: 默认的配置，对外暴露
     * @author lijx
     * @date 2022/5/20 21:46
     * @version 1.0
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
                http.authorizeRequests();
        log.info(permitAllUrlProperties.getUrls().toString());
        permitAllUrlProperties.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated().and().csrf().disable();
    }

    /**
     * ResourceServerSecurityConfigurer主要配置以下几方面： tokenServices：ResourceServerTokenServices
     * 类的实例，用来实现令牌访问服务，如果资源服务和授权服务不在一块，就需要通过RemoteTokenServices来访问令牌
     * tokenStore：TokenStore类的实例，定义令牌的访问方式 resourceId：这个资源服务的ID 其他的拓展属性例如 tokenExtractor
     * 令牌提取器用来提取请求中的令牌。
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        UserAuthenticationConverter userTokenConverter = new HxUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userTokenConverter);
        remoteTokenServices.setRestTemplate(restTemplate);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
        resources
                .authenticationEntryPoint(hxAuthenticationEntryPoint)
                .accessDeniedHandler(hxAccessDeniedHandler)
                .tokenServices(remoteTokenServices);
    }
}
